package com.qdxwx.web.controller.user;

import com.alibaba.fastjson2.JSON;
import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.BaJiaYunUtils;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.course.CourseNodeService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.live.LiveGenseeService;
import com.qdxwx.data.service.user.UserBuyService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.course.CourseNode;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.enums.WebsiteProfileType;
import com.qdxwx.models.live.LiveGensee;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * Live章节接口
 * @author developer
 */
@Controller
@RequestMapping("/user/live")
public class UserLivePlayController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(UserLivePlayController.class);
	@Autowired
	private CourseService courseService;
	@Autowired
	private CourseNodeService courseNodeService;
	@Autowired
	private UserBuyService userBuyService;
	@Autowired
	private WebsiteProfileService websiteProfileService;
	@Autowired
	private LiveGenseeService liveGenseeService;

	/**
	 * 直播 检查 播放
	 *
	 * @param request
	 * @param nodeId  课程节点id
	 * @return
	 */
	@RequestMapping("/play.html")
	public String livePlayHtml(HttpServletRequest request, @RequestParam("nodeId") int nodeId) throws IOException {
		User user = LoginUser.getUser(request);
		if (ObjectUtils.isNull(user)) {
			request.setAttribute("success", false);
			request.setAttribute("url", "请登录后观看直播！");
			return getViewPath("ucenter/uc-live-play");
		}
		CourseNode courseNode = courseNodeService.get(nodeId);


		// 当传入数据不正确时直接返回
		if (ObjectUtils.isNull(courseNode)) {
			request.setAttribute("success", false);
			request.setAttribute("url", "直播章节不存在！");
			return getViewPath("ucenter/uc-live-play");
		}
		// 判断节点不可以试听
		else {
			boolean isBuy = userBuyService.checkIsBuy(user.getUserId(), ModuleType.COURSE.ordinal(), courseNode.getCourseId());
			if (!isBuy) {// 判断该课程不可以观看
				request.setAttribute("success", false);
				request.setAttribute("url", "该直播为收费直播，请购买后操作。！");
				return getViewPath("ucenter/uc-live-play");
			} else if (LocalDateTime.now().plusMinutes(15).isBefore(courseNode.getLiveBeginTime())) {
				request.setAttribute("success", false);
				request.setAttribute("url", "直播未开始，您可在直播前15分钟内进入直播！");
				return getViewPath("ucenter/uc-live-play");
			} else if (LocalDateTime.now().isAfter(courseNode.getLiveEndTime())) {
				request.setAttribute("success", false);
				request.setAttribute("url", "直播已结束！");
				return getViewPath("ucenter/uc-live-play");
			}
			try {
				String videoUrl = courseNode.getVideoUrl();
				//判断 直播供应商
				//展示互动
				if ("gensee".equals(courseNode.getSupplier())) {
					//生成 展示互动 认证K 用户id+展示互动直播id+当前时间戳
					String encodeStr = user.getUserId() + videoUrl.substring(videoUrl.indexOf("/site/s/") + 8, videoUrl.indexOf("/site/s/") + 16) + System.currentTimeMillis();
					String encoded = Base64.getEncoder().encodeToString(encodeStr.getBytes());
					CacheUtils.set(CacheConstants.INDEX_LIVE_GENSEEK, encoded, 15);//缓存15秒 ，过期后失效

					videoUrl += "?nickname=" + user.getDisplayName() + "&uid=" + 1000000000 + user.getUserId() + "&k=" + encoded;
					//展视互动直播
					LiveGensee liveGensee = new LiveGensee();
					liveGensee.setLiveId((long) nodeId);
					List<LiveGensee> liveGenseeList = liveGenseeService.queryLiveGenseeList(liveGensee);
					if (ObjectUtils.isNotNull(liveGenseeList)) {
						liveGensee = liveGenseeList.get(0);
						videoUrl += "&token=" + liveGensee.getStudentToken();
					}
				}
				/*如果是百家云*/
				else if ("baiJiaYun".equals(courseNode.getSupplier())) {
					Map<String, Object> baiJiaYun = websiteProfileService.getMap(WebsiteProfileType.baiJiaYun);
					//返回直播回放token
					videoUrl = BaJiaYunUtils.getReturnUrl(courseNode.getVideoUrl(), baiJiaYun);
					Map<String, Object> da = JSON.parseObject(videoUrl, Map.class);
					System.out.print("code：" + da.get("code").toString());
					if (da.get("code").toString().equals("0")) {
						Map<String, Object> da2 = JSON.parseObject(da.get("data").toString(), Map.class);
						videoUrl = baiJiaYun.get("PartnerDomain") + "web/playback/index?classid=" + courseNode.getVideoUrl() + "&token=" + da2.get("token");
					} else if (da.get("code").toString().equals("1")) {
						videoUrl = BaJiaYunUtils.getRoomUrl(request, courseNode.getVideoUrl(), "WEB", "student", baiJiaYun);
					}
				}
				//网站开关配置
				request.setAttribute("success", true);
				request.setAttribute("url", videoUrl);

			} catch (Exception ex) {
				logger.error(ex.getMessage());
				request.setAttribute("success", false);
				request.setAttribute("url", ex.getMessage());
			}
			return getViewPath("ucenter/uc-live-play");
		}
	}
	/**
	 * 直播 检查 播放
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/play/check.json")
	@ResponseBody
	public AjaxResult livePlay(HttpServletRequest request) {
		long userId = LoginUser.getUserId(request);
		if (userId <= 0) {
			return AjaxResult.auth("请登录后观看直播！");
		}
		int nodeId = TKConvert.toInteger(request.getParameter("nodeId"));
		//Map<String,Object> baiJiaYun =  websiteProfileService.getMap(WebsiteProfileType.baiJiaYun);

		CourseNode courseNode = courseNodeService.get(nodeId);
		// 当传入数据不正确时直接返回
		if (ObjectUtils.isNull(courseNode)) {
			return AjaxResult.error("直播章节不存在！");
		}
		if (LocalDateTime.now().plusMinutes(15).isBefore(courseNode.getLiveBeginTime())) {
			return AjaxResult.error("直播未开始，您可在直播前15分钟内进入直播！");
		}
		if (LocalDateTime.now().isAfter(courseNode.getLiveEndTime())) {
			return AjaxResult.error("直播已经结束！");
		}
		if (courseNode.getFree() != 1) {
			// 判断节点不可以试听
			boolean isBuy = userBuyService.checkIsBuy(userId, ModuleType.COURSE.ordinal(),courseNode.getCourseId());
			if (!isBuy) {// 判断该课程不可以观看
				return AjaxResult.forbid("您还未报名此课程，请报名报观看。");
			}
		}
		return AjaxResult.success(nodeId);
	}


	/**
	 * 根据直播id获得 跟现在 最近的一个直播播放
	 *
	 * @param request
	 * @param courseId 课程id
	 * @return
	 */
	@RequestMapping("/play/getId.json")
	@ResponseBody
	public AjaxResult nowLivePlay(HttpServletRequest request, @RequestParam("courseId") int courseId) throws IOException {
		long userId = LoginUser.getUserId(request);
		if (userId <= 0) {
			return AjaxResult.error("请登录后观看直播！");
		}
		Course course = courseService.get(courseId);
		// 当传入数据不正确时直接返回
		if (ObjectUtils.isNull(course)) {
			return AjaxResult.error("直播不存在！");
		} else {
			boolean isBuy = userBuyService.checkIsBuy(userId, ModuleType.COURSE.ordinal(),courseId);
			if (!isBuy) {// 判断该课程不可以观看
				return AjaxResult.error("该直播为收费直播，请购买后操作。");
			} else {
				CourseNode courseNode = courseNodeService.getLiving(courseId, LocalDateTime.now().plusMinutes(-15));
				if (ObjectUtils.isNotNull(courseNode)) {
					return AjaxResult.success(courseNode.getNodeId());
				} else {
					return AjaxResult.error("暂无直播中的课程，请查看直播课程表！");
				}
			}
		}
	}
}